package cooperated

import (
	"fmt"

	"gddgame.cc/galaxy/common/namespaces/cooperate"
	"gddgame.cc/galaxy/common/namespaces/cooperate/structure"
	"gddgame.cc/galaxy/utils"
)

func (logic *TypeMap) OnListen(data structure.Data, selfIdentity int, listen *ListenLogic, time int64) {
	listenData := make([]cooperate.OperateData, len(listen.Nodes))
	target := structure.NewBaseDataFrom(data)
	if listen.Switch {
		listenData = append(listenData, cooperate.NewOperateData(cooperate.BatchUpdateOperate, &cooperate.UpdateOperateData{
			Data: *target,
			Operates: []cooperate.UpdateOperateContent{{
				Operate: cooperate.ChangeData,
				Key:     Listen,
				Value:   listen.Nodes,
			}},
		}))
		//fmt.Println("add listen", data.GetDataType(), data.GetId(), listen.Nodes, listen.Events)
		logic.AddLinks(data.GetItem(), ListenRelation, listen.Nodes)
	} else {
		listenData = append(listenData, cooperate.NewOperateData(cooperate.BatchUpdateOperate, &cooperate.UpdateOperateData{
			Data: *target,
			Operates: []cooperate.UpdateOperateContent{{
				Operate: cooperate.ChangeData,
				Key:     Listen,
				Value:   nil,
			}},
		}))
		logic.RemoveLinks(data.GetItem(), ListenRelation, listen.Nodes)
	}
	updateData := cooperate.OperateContent{
		MapNoId:  logic.GetMapNoId(),
		Target:   target,
		Operates: listenData,
	}
	//if sm.FromStartUp(time)-sm.FromStartUp(sm.CurrentTime()) < -500 {
	//	debug.PrintStack()
	//}
	logic.PushOperate(updateData, time)

	if (listen.Events != nil && len(listen.Events) > 0) || (listen.EventsData != nil && len(listenData) > 0) {
		if listen.Events != nil && len(listen.Events) > 0 {
			events := logic.GetEventsCache(logic, data, listen.Events)
			listen.EventsData = events
			//fmt.Println("event:", data, listen.Events, events)
		}
		_, itemList, identityList := logic.GetItemList(listen.Nodes, time)
		//fmt.Println("item:", itemList, identityList, selfIdentity)
		// 不用考虑建筑问题，部队进入建筑就会取消占位
		if itemList == nil || identityList == nil {
			return
		}
		for _, item := range itemList {
			if item == nil {
				continue
			}
			r := structure.NewBaseDataByte(item)
			if r.DataType == data.GetDataType() && utils.ToInt(r.Id) == utils.ToInt(data.GetId()) {
				continue
			}
			pp := logic.GetDetailCache(logic, r)
			if pp.ToBool(Ignore) {
				continue
			}
			tIdentity := pp.ToInt(Identity)
			position := pp.ToBytes(Position)
			isPartner, isEnemy := logic.JudgeIdentity(selfIdentity, tIdentity)
			fmt.Println("r", r, data, selfIdentity, pp.ToInt(Identity), isPartner, isEnemy)
			switch listen.Identity {
			case EnemyTargetIdentity:
				if !isEnemy {
					continue
				}
			case PartnerTargetIdentity:
				if !isPartner {
					continue
				}
			}
			for index, e := range listen.EventsData {
				if e != nil {
					logic.Mode(logic, data, data, *e, time, cooperate.NewModeExtend([]interface{}{r.GetDataType(), r.GetId(), listen.Events[index]}, logic.GetMapNoId(), nil, position))
					break
				}

			}
		}
	}
}
